/*
 * @Author: lixu lixu@puchigames.com
 * @Date: 2025-01-03 16:49:48
 * @LastEditors: lixu lixu@puchigames.com
 * @LastEditTime: 2025-09-17 09:47:17
 * @FilePath: /go-helper/ixRedis/set.go
 * @Description: Redis 集合操作
 */

package ixRedis

import "github.com/garyburd/redigo/redis"

// SAdd 添加集合成员
func (c *Client) SAdd(key string, members ...interface{}) (int64, error) {
	if len(members) == 0 {
		return 0, nil
	}

	conn, err := c.getConn()
	if err != nil {
		return 0, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	args := make([]interface{}, len(members)+1)
	args[0] = fullKey
	for i, member := range members {
		args[i+1] = member
	}

	return redis.Int64(conn.Do("SADD", args...))
}

// SRem 删除集合成员
func (c *Client) SRem(key string, members ...interface{}) (int64, error) {
	if len(members) == 0 {
		return 0, nil
	}

	conn, err := c.getConn()
	if err != nil {
		return 0, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	args := make([]interface{}, len(members)+1)
	args[0] = fullKey
	for i, member := range members {
		args[i+1] = member
	}

	return redis.Int64(conn.Do("SREM", args...))
}

// SMembers 获取集合所有成员
func (c *Client) SMembers(key string) ([]string, error) {
	conn, err := c.getConn()
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	return redis.Strings(conn.Do("SMEMBERS", fullKey))
}

// SIsMember 检查成员是否在集合中
func (c *Client) SIsMember(key string, member interface{}) (bool, error) {
	conn, err := c.getConn()
	if err != nil {
		return false, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	count, err := redis.Int64(conn.Do("SISMEMBER", fullKey, member))
	return count > 0, err
}

// SCard 获取集合成员数量
func (c *Client) SCard(key string) (int64, error) {
	conn, err := c.getConn()
	if err != nil {
		return 0, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	return redis.Int64(conn.Do("SCARD", fullKey))
}
